#!/usr/bin/perl
use strict;
use warnings;
use English '-no_match_vars';
use EBox;
use EBox::Sudo;
use EBox::Util::Certificate;

my ($destDir, $issuer) = @ARGV;

my $RSA_LENGTH = 4096;

unless (defined $destDir) {
   print "Usage:$0 prefix [issuer]\n";
   exit 1;
}

_checkCredentials();
EBox::init();
_checkPrograms();

if (not EBox::Sudo::fileTest('-d', $destDir)) {
    print "SSL directory $destDir does not exist, we will create it\n";
}

my ($keyFile, $keyUpdated)  = EBox::Util::Certificate::generateRSAKey($destDir, $RSA_LENGTH);
if ($keyUpdated) {
    print "New key file generated: '$keyFile'\n";
    my $certFile = EBox::Util::Certificate::generateCert($destDir, $keyFile, $keyUpdated, $issuer);
    print "New certificate file generated: '$certFile'\n";
    my $pemFile = EBox::Util::Certificate::generatePem($destDir, $certFile, $keyFile, $keyUpdated);
    print "New PEM file generated: '$pemFile'\n";
}
print "All server's certificate files in place\n\n";

sub _checkCredentials
{
  if ($EUID != 0) {
    die "This script can only be run by root";
  }

  my ($gid) = split '\s', $EGID;
  if ($gid != 0) {
    die "To run this script your primary group must be set to root";
  }
}

sub _checkPrograms
{
  my @programs = qw(openssl);
  foreach (@programs) {
    system "which $_ 2>&1 > /dev/null";
    if ($? != 0) {
      die "$_ program not found in the path. Make sure it is installed";
    }
  }

}
1;
